﻿using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WindowsFormsWeChartDemo.Models;

namespace WindowsFormsWeChartDemo.Common
{
    public class WeChartHelper
    {
        public delegate void AddToQueueHandler(SendMessageModel model);
        public delegate void CompletedHandler(SendMessageModel model);
        public delegate void OtherHandler(string msg);
        public CompletedHandler SendCompletedEvent;
        public AddToQueueHandler AddToQueueEvent;
        public OtherHandler OtherEvent;

        private MessageQueue messageQueue = new MessageQueue();
        private Logger logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 将消息加入到队列
        /// </summary>
        /// <param name="model"></param>
        public void AddMessage(SendMessageModel model)
        {
            Message msg = new Message();
            if (null != model)
            {
                msg.touser = model.openid;
                msg.template_id = model.template_id;
                var data = JsonConvert.DeserializeObject<Dictionary<string, DataModel>>(model.message);
                msg.data = data;
            }
            AddToQueueEvent?.Invoke(model);
            messageQueue.AddMessgae(new MessageQueueModel(msg, model));
        }

        /// <summary>
        /// 异步发送消息
        /// </summary>
        /// <returns></returns>
        public async Task SendMessageAsync()
        {
            if (messageQueue.IsMessageQueueAvailable)
            {
                MessageQueueModel model = messageQueue.GetMessage();
                logger.Info($"准备发送消息：AppID：{model.sendMessageModel.appid},OpenId:{model.message.touser},Message:{model.sendMessageModel.message}");
                string token = await TokenHelper.GetAccessTokenAsync(model.sendMessageModel.appid, model.sendMessageModel.appsecret);

                string url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={token}";
                string postData = JsonConvert.SerializeObject(model.message);
                string str = await HttpPostData(url, postData);
                logger.Info($"返回结果：{str}");
                model.sendMessageModel.Result = str;
                SendCompletedEvent?.Invoke(model.sendMessageModel);
            }
            else
            {
                OtherEvent?.Invoke($"{DateTime.Now.ToString("yyyyMMddHHmmss")}-队列中没有待发送消息");
            }
        }
        public async Task<string> HttpPostData(string posturl, string postData)
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {

                    HttpContent content = new StringContent(postData);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    var response = await client.PostAsync(posturl, content);
                    response.EnsureSuccessStatusCode();
                    string body = await response.Content.ReadAsStringAsync();
                    return body;
                }
                catch (Exception ex)
                {
                    OtherEvent?.Invoke($"执行HttpPost出错:{ex.Message}");
                    logger.Error(ex);
                    return string.Empty;
                } 
            }
        }
        
    }
}
